const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const User = require('./mongo/User');
const Material = require('./Material');

const Cart = sequelize.define('Cart', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  material_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'materials',
      key: 'id'
    }
  },
  quantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 1,
    validate: {
      min: 1
    }
  },
  status: {
    type: DataTypes.ENUM('pending', 'completed', 'cancelled'),
    allowNull: false,
    defaultValue: 'pending'
  },
  is_watermark: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    allowNull: false
  },
  expires_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: () => {
      const date = new Date();
      date.setDate(date.getDate() + 7); // 默认7天后过期
      return date;
    },
    comment: '购物车项过期时间'
  }
}, {
  tableName: 'cart',
  indexes: [
    {
      fields: ['user_id']
    },
    {
      fields: ['material_id']
    },
    {
      fields: ['expires_at']
    },
    {
      fields: ['status']
    },
    {
      fields: ['user_id', 'material_id'],
      unique: true
    }
  ],
  underscored: true // 自动将camelCase转换为snake_case
});

// 设置关联关系
Cart.belongsTo(User, {
  foreignKey: 'user_id',
  as: 'user'
});

Cart.belongsTo(Material, {
  foreignKey: 'material_id',
  as: 'material'
});

// 添加实例方法
Cart.prototype.isExpired = function() {
  return new Date() > new Date(this.expires_at);
};

module.exports = Cart;